"""
python fujian2_svm_predict.py
"""
import pandas as pd
import numpy as np
from sklearn.svm import SVR
import os
import json
import matplotlib.pyplot as plt


def Prophet_predict_single_category(input_path, output_path):
    # 读取输入的 JSON 文件
    with open(input_path, 'r') as f:
        data = json.load(f)

    # 将 JSON 数据转换为 DataFrame
    df = pd.DataFrame(data)
    df['ds'] = pd.to_datetime(df['date'])
    df.rename(columns={'sales': 'y'}, inplace=True)

    # 准备数据用于训练
    X = np.arange(len(df)).reshape(-1, 1)
    y = df['y'].values

    # 创建 SVM 模型对象
    model = SVR()

    # 拟合数据
    model.fit(X, y)

    # 构建未来日期范围对应的索引
    future_index = np.arange(len(df), len(df) + (pd.to_datetime('2023-09-30') - pd.to_datetime('2022/7/1')).days).reshape(-1, 1)

    # 进行预测
    forecast = model.predict(future_index)

    # 创建包含预测日期的数据框
    future_dates_length = len(forecast)
    future_dates = pd.date_range(start='2023-07-01', periods=future_dates_length)
    result_df = pd.DataFrame({'ds': future_dates, 'yhat': forecast})

    # 将结果转换回 JSON 格式
    result_json = result_df[['ds', 'yhat']].to_json(orient='records')
    result_json = json.loads(result_json)

    # 创建输出目录如果不存在
    output_dir = os.path.dirname(output_path)
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    # 写入输出 JSON 文件
    with open(output_path, 'w') as f:
        json.dump(result_json, f)

    # 绘制原始数据和预测数据的图像
    plt.figure(figsize=(10, 6))
    plt.plot(df['ds'], df['y'], label='Original Data')
    plt.plot(result_df['ds'], result_df['yhat'], label='Predicted Data')
    plt.legend()

    # 创建图像输出目录如果不存在
    graph_dir = os.path.join('../fujian/fujian2/svm/gragh')
    if not os.path.exists(graph_dir):
        os.makedirs(graph_dir)

    # 保存图像
    plt.savefig(os.path.join(graph_dir, os.path.basename(input_path).replace('.json', '.png')))


if __name__ == "__main__":
    # 示例调用
    input_path = "../fujian/fujian2/groupByCategory/category_category1.json"
    output_path = "../fujian/fujian2/svm/json_output/category_category1_output.json"
    Prophet_predict_single_category(input_path, output_path)
